import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {CommonTool} from '../../common/common.tool';
import {environment} from '../../../environments/environment';
import {ShareFileService} from './share-file.service';
import {ActivatedRoute} from '@angular/router';
import {HTTP_URLS} from '../base-http.url';


@Component({
  selector: 'app-file-management',
  templateUrl: './share-file.component.html',
  styleUrls: ['./share-file.component.scss']
})
export class ShareFileComponent implements OnInit {

  public checkedModel: any;
  public isAllChecked: boolean;
  public currentObj: any;
  public isChecked: boolean;
  public environment = environment;
  public movieData: Array<object> = [];
  public showVideoPlay = false;
  public videoUrl: string;
  public showMusicPlay = false;
  public musicUrl;
  public picturePlay = false;
  public pictureUrl;

  public labelModel = [];
  public tableModel = [];
  public shareId;
  public isDrawCodeVisible = false;
  public drawCode = '';


  constructor(public shareFileService: ShareFileService,
              public commonTool: CommonTool,
              public ele: ElementRef,
              public activatedRoute: ActivatedRoute) {
    this.currentObj = {id: 0, parentId: '', fileId: ''};
    for (const data of this.environment.config.video) {
      this.movieData.push({
        path: this.environment.config.url + data.path,
        origin: this.environment.config.url + data.origin
      });
    }
    const code = this.activatedRoute.snapshot.params['code'];
    this.shareFileService.inspectShareFile(code).subscribe(res => {
      if (this.commonTool.notNull(res)) {
        this.shareId = res.shareId;
        this.getData();
      } else {
        this.isDrawCodeVisible = true;
      }
    });
  }

  /**
   * 验证提取码
   */
  public verifyDrawCode() {
    const code = this.activatedRoute.snapshot.params['code'];
    this.shareFileService.shareVerify({
      code,
      drawCode: this.drawCode
    }).subscribe(res => {
      if (this.commonTool.notNull(res.shareId)) {
        this.isDrawCodeVisible = false;
        this.shareId = res.shareId;
        this.getData();
      }
    });
  }

  /**
   * 获取后缀
   */
  public getSuffix(name) {
    let suffix = '';
    if (this.commonTool.notNull(name)) {
      suffix = name.substring(name.lastIndexOf('.'), name.length);
    }
    return suffix.toLowerCase();
  }

  /**
   * 视频播放
   */
  public videoPlay(fid) {
    this.showVideoPlay = true;
    this.videoUrl = HTTP_URLS.shareDownload + this.shareId + '?fid=' + fid;
  }

  /**
   * 播放音乐
   */
  public videoMusic(fid) {
    this.showMusicPlay = true;
    this.musicUrl = HTTP_URLS.shareDownload + this.shareId + '?fid=' + fid;
  }

  /**
   * 打开图片
   */
  public openPicture(fid) {
    this.picturePlay = true;
    this.pictureUrl = HTTP_URLS.shareDownload + this.shareId + '?fid=' + fid;
  }

  /**
   * 下载文件
   */
  public downloadFile(fid) {
    location.href = HTTP_URLS.shareDownload + this.shareId + '?fid=' + fid;
  }


  // 初始化
  ngOnInit(): void {

  }

  // 标签点击事件
  public label(data, index) {
    if (data.id === '' && index === 0) {
      this.labelModel = [];
    }
    this.labelModel.splice(index + 1, this.labelModel.length - (index + 1));
    this.getData(data);
  }

  // 获取数据
  public getData(data?) {
    this.checkedModel = [];
    this.isAllChecked = false;
    this.tableModel = [];
    if (!this.commonTool.notNull(data)) {
      data = {};
    }
    if (!this.commonTool.notNull(data.id)) {
      data.id = '';
    }
    this.currentObj = data;
    this.shareFileService.shareFile(this.shareId, {parentId: data.id}).subscribe(res => {
      const array = [];
      if (this.commonTool.notNull(res['folders'])) {
        for (const arr of res['folders']) {
          arr.isFile = false;
          array.push(arr);
        }
      }
      if (this.commonTool.notNull(res['files'])) {
        for (const r of res['files']) {
          r.isFile = true;
          array.push(r);
        }
      }
      this.tableModel = array;
    });
  }

  // 点击
  public trClick(event, data) {
    if (!data.isFile) {
      this.labelModel.push(data);
      this.getData(data);
    }
  }

  // 选择
  public checkboxChoice(data) {
    // 全部选择
    this.isAllChecked = this.tableModel.every((item) => {
      return this.checkedModel[item.id];
    });
    // 设置选中后可以操作的按钮
    this.isChecked = true;
    this.tableModel.forEach(item => {
      if (this.checkedModel[item.id]) {
        this.isChecked = false;
      }
    });
    // 选中，取消
    if (this.checkedModel[data.id]) {
      this.checkedModel[data.id] = data;
    } else {
      delete this.checkedModel[data.id];
    }
  }

  // 全选
  public checkAll() {
    if (this.isAllChecked) {
      for (const folder of this.tableModel) {
        this.checkedModel[folder.id] = folder;
      }
      this.isChecked = false;
    } else {
      for (const folder of this.tableModel) {
        delete this.checkedModel[folder.id];
      }
      this.isChecked = true;
    }
  }

  // 排序
  public sort(event, ...events): void {
    for (const ev of events) {
      if (ev.nzSortKey !== event.key) {
        ev.nzSort = null;
      }
    }
    const array = this.tableModel;
    if (event.value === 'ascend') {
      if (event.key === 'name') {
        array.sort((a, b) => {
          return a[event.key].localeCompare(b[event.key], 'zh-CN');
        });
      } else if (event.key === 'updateTime') {
        array.sort((a, b) => {
          return new Date(a[event.key].replace(/-/g, '/')).getTime() - new Date(b[event.key].replace(/-/g, '/')).getTime();
        });
      }
    } else if (event.value === 'descend') {
      array.reverse();
    } else {
      this.getData(this.currentObj);
    }
    this.tableModel = JSON.parse(JSON.stringify(array));
  }

  // 返回上级
  public revert() {
    if (this.labelModel.length <= 1) {
      this.getData({id: ''});
      this.labelModel.splice(this.labelModel.length - 1, 1);
      this.currentObj = {id: ''};
    } else {
      this.getData({id: this.currentObj.parentId});
      const data = this.labelModel.splice(this.labelModel.length - 1, 1);
      this.currentObj = data[0];
    }
  }

  public playMovie(url) {
    this.showVideoPlay = true;
    this.videoUrl = url;
  }

  public closeMovie() {
    this.showVideoPlay = false;
    const videoEle = this.ele.nativeElement.querySelector('#videoPlayer');
    videoEle.pause();
  }

  public closeMusic() {
    this.showMusicPlay = false;
    const videoEle = this.ele.nativeElement.querySelector('#musicPlay');
    videoEle.pause();
  }

  public closePicture() {
    this.picturePlay = false;
  }
}
